package com.cis467.mrball.backend;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.cis467.mrball.HighScore;
import com.cis467.mrball.parts.Level;



public final class OnlineContent {
	
	// TODO save this as a shared preference, or even better, in the database
	public static String base_url = "http://danieljaglowski.com/a_gameContent/";	
	
	public static void set_HighScore(HighScore hs){
		String serverRequest = base_url + "setHighScore.php?";
		
		serverRequest += "ln=" + hs.getLevelName();
		serverRequest += "&ls=" + hs.getTime();
		serverRequest += "&usr=" + hs.getUserName();
		
		try{
			make_server_request(serverRequest);
		}catch(Exception e){
			//handle error
		}
	}
	
	// TODO update for new LevelWrapper format
	public static String upload_Level(Level newLevel)throws Exception{
		String serverRequest = base_url + "Maps/";
		

		
		//JSONObject obj = new JSONObject();
		
//		obj.put("u", LocalContent.getUserID());
//		obj.put("k", LocalContent.getUserKey());
//		obj.put("n", newLevel.getName());
//		obj.put("x", newLevel.toString());
		
		
//		Map<String, String> pairs = new HashMap<String, String>();
//		pairs.put("u", LocalContent.getUserID());
//		pairs.put("k", LocalContent.getUserKey());
//		pairs.put("n", newLevel.getName());
//		pairs.put("x", newLevel.toString());
		
		
		
		
		List<NameValuePair> post = new ArrayList<NameValuePair>(2);
		post.add(new BasicNameValuePair("u",LocalContent.getUserID()));
		post.add(new BasicNameValuePair("k",LocalContent.getUserKey()));
	//	post.add(new BasicNameValuePair("n",newLevel.getName()));
		post.add(new BasicNameValuePair("x",newLevel.toString()));
		try{
			//return make_server_request(serverRequest);
			return make_server_post(serverRequest, post);
		}catch(Exception e){
			e.printStackTrace();
		}
		return "return";
	}
	
	/*  
	 * Returns a list of high scores associated with MBlevel
	 */
	public static HighScore[] get_HighScores(Level level){
		
		String serverRequest = base_url += "getHighScore.php?lvl_name=";
	//	serverRequest += level.getName();
		
		String fromServer = null;
		
		try{
			fromServer = make_server_request(serverRequest);
			
		}catch(Exception e){
			return null;
		}
		
		return build_HighScores(fromServer);
	}
	
	
	/*
	 * returns null if build was unsuccessful
	 */
	public static HighScore[] build_HighScores(String highScores){
		
    	String[] parsed_highScores = null;
    	HighScore[] lvlHighScores = null;
		try{
			parsed_highScores = highScores.split(":");
		
		if(parsed_highScores.length == 0)
			return null;
		
    	if(parsed_highScores.length == 1){
    		
    			lvlHighScores =  new HighScore[1];
    			lvlHighScores[0] = new HighScore(parsed_highScores[0]);    		
  
    	}else if(parsed_highScores.length > 1){
 
    		lvlHighScores = new HighScore[parsed_highScores.length];
    		for(int i = 0; i < parsed_highScores.length; i++)
    			lvlHighScores[i] = new HighScore(parsed_highScores[i]);
    	}
		}catch(Exception e){
			return null;
		}
		return lvlHighScores;		

	}
	
	
	/*
	 * returns text from HTTP Request to param url
	 */
	public static String make_server_request(String url) throws Exception{
		String fromServer;
		
		HttpClient client = new DefaultHttpClient();
		HttpGet httpGet = new HttpGet(url);
		
	    HttpResponse response = client.execute(httpGet);
		  
		if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
		  fromServer = EntityUtils.toString(response.getEntity());
		else
		  throw new Exception("Http return status : " + response.getStatusLine().getStatusCode());
		  
		return fromServer;
	}
	
	/*
	 * executes a HTTP post to parameter url
	 */
	private static String make_server_post(String url, List<NameValuePair> post) throws Exception {
		
		HttpClient client = new DefaultHttpClient();
		HttpPost httpPost = new HttpPost(url);
       
		//httpPost.setHeader("Accept", pairs.contentType);
		
		httpPost.setEntity(new UrlEncodedFormEntity(post));
		
	    HttpResponse response = client.execute(httpPost);
		  
		if(response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
		  throw new Exception("Http return status : " + response.getStatusLine().getStatusCode());
		return EntityUtils.toString(response.getEntity());
	}
	
	
	public static ArrayList<Level> download_level() throws Exception{
		String levelFromServer = "";
		String serverRequest = base_url + "Maps/";
		
		levelFromServer = make_server_request( serverRequest );

		String[] levelStrings = levelFromServer.split("111123next321111");
		
		ArrayList<Level> levels = new ArrayList<Level>();
		
		for (String levelStr : levelStrings) {
			
			if(!levelStr.equals(""))
				try {
					levels.add(LocalContent.convertXML(levelStr));
				}
				catch (Exception e){
					
				}
		}
		
		return levels;
	}
	
	/*  
	 * Returns a list of high scores associated with MBlevel
	 */
	public static HighScore[] get_myHighScores(){
		
		String serverRequest = base_url += "getHighScore.php?u=";
		//serverRequest += GameManagement.get_userName();
		
		String fromServer = null;
		
		try{
			fromServer = make_server_request(serverRequest);
		}catch(Exception e){
			return null;
		}
		
		return build_HighScores(fromServer);
	}

	
	// creates a new user acount.
	public static void newUser() {
		String server, serverRet[];
		String ret ="";
		boolean good = false;
		while(!good){
		 try {
			server = make_server_request(base_url+"Users");
			serverRet = server.split(",");
			//if(ret.equals("ok"))
				good = true;
		 } catch (Exception e) {
			// who knows
			server = "";
		 }
		 if(good){
		  try {
			LocalContent.saveFile( server.replaceAll(",", "\n"), "", LocalContent.idFile) ;
		  } catch (Exception e) {
			good = false;
		  }
		 }
		}
		
		
	}



}
